package edu.uclm.esi.tysw.podtube.acciones;

import java.sql.SQLException;

import com.opensymphony.xwork2.ActionSupport;

import edu.uclm.esi.tysw.podtube.domain.Usuario;
import edu.uclm.esi.tysw.podtube.exceptions.UserAlreadyExistingException;

public class AltaUsuario extends ActionSupport {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private String email;
	private String pwd1, pwd2;
	private Exception exception;
	
	public String execute() {
		try {
			Usuario user=new Usuario(email);
			user.insert(this.pwd1);
			return SUCCESS;
		} catch (UserAlreadyExistingException e) {
			this.exception=e;
			return ERROR;
		} catch (SQLException e) {
			this.exception=e;
			return ERROR;
		} 
	}
	
	@Override
	public void validate() {
		if (this.pwd1==null || this.pwd2==null || this.pwd1.length()==0 || this.pwd2.length()==0) {
			super.addFieldError("pwd1", "The password cannot be empty");
		}
		if (!this.pwd1.equals(this.pwd2)) {
			super.addFieldError("pwd2", "The passwords do not match");
		}
		if (this.email==null || this.email.length()==0) {
			super.addFieldError("email", "Tha email cannot be empty");
		}
		if (this.email!=null && this.email.length()>45) {
			super.addFieldError("email", "The mail cannot have more than 45 characters");
		}
		boolean tieneBlancos=false;
		int arrobas=0;
		for (int i=0; i<this.email.length(); i++) {
			if (Character.isWhitespace(this.email.charAt(i)))
				tieneBlancos=true;
			if (this.email.charAt(i)=='@')
				arrobas++;
		}
		if (tieneBlancos) {
			super.addFieldError("email", "The email cannot contain blank spaces");
		}
		if (arrobas==0) {
			super.addFieldError("email", "Symbol @ is missing");
		}
		if (arrobas>1) {
			super.addFieldError("email", "Bad format for the email");
		}
	}

	public String getEmail() {
		return email;
	}

	public void setEmail(String email) {
		this.email = email;
	}

	public void setPwd1(String pwd1) {
		this.pwd1 = pwd1;
	}

	public void setPwd2(String pwd2) {
		this.pwd2 = pwd2;
	}

	public void setException(Exception exception) {
		this.exception = exception;
	}

	public Exception getException() {
		return exception;
	}
}
